package com.gxa.meiye.sso.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.meiye.core.exception.BusinessException;
import com.gxa.meiye.core.exception.ExceptionCode;
import com.gxa.meiye.sso.entity.Consumer;
import com.gxa.meiye.sso.repository.UserRepository;
import com.gxa.meiye.sso.service.ConsumerService;
import com.gxa.meiye.sso.utils.SignInUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zy
 * @CreateTime: 2022-07-19  21:34
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class ConsumerServiceImpl implements ConsumerService {
    @Autowired
    RedisTemplate<String,Object> redisTemplate=null;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    HttpServletRequest request=null;
    public static final String SALT="abcde";
    //public static final String DAY="day";
    @Override
    public String login(String phone, String code) throws Exception {



            //1.获取redis服务器存储的验证码
            Object rediscode =  redisTemplate.opsForValue().get(SmsServiceImpl.LOGIN_SMS+phone);
            //验证码失效的判断,如果为空则抛出异常
            if (StringUtils.isEmpty(rediscode)) {
                throw new BusinessException(ExceptionCode.EXPIRE_CODE);
            }
            //对验证码做校验, 如果不一致则抛出异常
            if (!code.equals(rediscode)) {
                throw new BusinessException(ExceptionCode.WRONG_CODE);
            }
            //校验完成, 从mysql数据库中查找用户信息
           Consumer findUser = userRepository.findAllByPhoneEquals(phone);
            //校验完成, 删除验证码
            redisTemplate.delete(SmsServiceImpl.LOGIN_SMS+phone);
            //如果用户不存在, 则匿名注册,匿名格式: "用户:"+phone , 并指定用户状态
            if (StringUtils.isEmpty(findUser)){
                //创建实体类
                findUser=new Consumer();
                //设置用户状态 1为正常，2为禁用
                findUser.setStatus(0);
                //设置电话
                findUser.setPhone(phone);
                //注册时间
                findUser.setRegistrationTime(LocalDateTime.now());
            }
            //如果用户存在, 但状态不为1,表示冻结状态, 抛出异常
            if (findUser.getStatus()!=0){
                throw new BusinessException(ExceptionCode.WRONG_USER_STATUS);
            }
        //获取连续登录天数
       // int dayNumber=1;
        Consumer time = userRepository.time(phone);
        System.out.println(time);
        if (!StringUtils.isEmpty(time)) {
            //获取上一次的登录时间
        LocalDateTime lastLogin = time.getLastLogin();
        //获取上一次的连续天数
        Integer continuousLoginDate = time.getContinuousLoginDate();

            int year = lastLogin.getYear();
            Month month = lastLogin.getMonth();
            int dayOfYear = lastLogin.getDayOfYear();
            LocalDateTime with = lastLogin.with(TemporalAdjusters.lastDayOfYear());
            int dayOfYear2 = with.getDayOfYear();
            System.out.println(year + "" + dayOfYear + "" + month+"最后一天"+dayOfYear2);
            //当前时间
            LocalDateTime now = LocalDateTime.now();
            //now.with(TemporalAdjusters.lastDayOfYear());
            int year1 = now.getYear();
            Month month1 = now.getMonth();
            int dayOfYear1 = now.getDayOfYear();

            System.out.println(year1 + "" + dayOfYear1 + "" + month1);
            int number = dayOfYear1 - dayOfYear;
            int yearNumber = year1 - year;
            if (year == year1 && number == 1) {
                continuousLoginDate++;
            } else if (year == year1&&dayOfYear1==dayOfYear){

            }
            else if (yearNumber == 1 &&(dayOfYear==dayOfYear2)&& dayOfYear1 == 1) {
                continuousLoginDate++;
            }else {
                continuousLoginDate=1;
            }
            findUser.setContinuousLoginDate(continuousLoginDate);
        }else {
            int continuousLoginDate = 1;
            findUser.setContinuousLoginDate(continuousLoginDate);
        }
        //获取最后一次登录时间
            findUser.setLastLogin(LocalDateTime.now());



        //List<Consumer> time = userRepository.time(phone);
       /* if (StringUtils.isEmpty(time)){
            findUser.setContinuousLoginDate(1);
        }else {
            SignInUtils signInUtils=new SignInUtils();
            System.out.println(time);
            List<LocalDateTime> localDateTimes=new ArrayList<>();
            for (int i=0;i<time.size();i++){
                Consumer consumer= time.get(i);
                localDateTimes.add(consumer.getLastLogin());
            }
            System.out.println(localDateTimes);
            int continuousSignInDay = signInUtils.getContinuousSignInDay(localDateTimes);
            System.out.println(continuousSignInDay);
            findUser.setContinuousLoginDate(continuousSignInDay);
        }*/


        //userRepository.
            //获取登录类型 1pc
           // findUser.setLoginType(1);
            //如果用户存在,获取上次的token,如果不为空移除redis中上一次的登录信息
            //生成token，存储登录信息(json),利用处理后的UUID


           /* Integer time=0;
            if (findUser.getLoginType()==1){
                time=2;
            }else if (findUser.getLoginType()==2){
                time=2;
            }else{
                time=24*31;
            }*/
    //Object redisToken = redisTemplate.opsForValue().get(SALT + findUser.getToken());
//           /* Boolean redisToken=redisTemplate.hasKey(SALT + findUser.getToken());
//            System.out.println(redisToken);
//            if (redisToken){
//                System.out.println(findUser.getToken());
//
//                redisTemplate.delete(SALT+findUser.getToken());
//
//            }
        Boolean redisToken=redisTemplate.hasKey(SALT + findUser.getToken());
        System.out.println(redisToken);
        if (redisToken){
            System.out.println(findUser.getToken());

            redisTemplate.delete(SALT+findUser.getToken());

        }
       // System.out.println(findUser);
            String token= UUID.randomUUID().toString().replace("-","");
            findUser.setToken(token);
            String key=SALT+token;
            // 设置ip,设置token,更新mysql
            Consumer save = userRepository.save(findUser);
        System.out.println(save);
            ObjectMapper objectMapper=new ObjectMapper();
            String value = objectMapper.writeValueAsString(save);
            redisTemplate.opsForValue().set(key,value,2, TimeUnit.HOURS);
            //处理登录*/

            //return token;
           return token;
        }


    @Override
    public Consumer checkToken(String token) throws Exception {
        //获取key值
        String key=SALT+token;
        //绑定key值
        BoundValueOperations<String, Object> stringOps = redisTemplate.boundValueOps(key);
        //校验
        if(StringUtils.isEmpty(stringOps.get())){
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
        stringOps.expire(2,TimeUnit.HOURS);
        ObjectMapper objectMapper=new ObjectMapper();
        Consumer consumer = objectMapper.readValue(stringOps.get().toString(), Consumer.class);
        //System.out.println(user);
        return consumer;

    }
}
